package com.nowadays.mobile.db;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;

import com.nowadays.mobile.model.Focus;
import com.nowadays.mobile.utils.FocusUtils;

import java.util.ArrayList;

public class DbProvider extends SQLiteOpenHelper {
  private static DbProvider instance;

  public static DbProvider getInstance(Context context) {
    if (instance == null) {
      synchronized (DbProvider.class) {
        if (instance == null) {
          instance = new DbProvider(context);
        }
      }
    }
    return instance;
  }

  private DbProvider(Context context) {
    super(context, name, null, version);
  }

  private static String name = "focus";
  private static int version = 1;

  @Override
  public void onCreate(SQLiteDatabase db) {
    String sql = "create table " + FocusTable.TABLE_NAME + "(" + FocusTable._ID
        + " INTEGER PRIMARY KEY AUTOINCREMENT,"
        + FocusTable.FOCUS_STARTTIME + " INTEGER," + FocusTable.FOCUS_ENDTIME + " INTEGER,"
        + FocusTable.FOCUS_DURATION + " INTEGER" + ");";
    db.execSQL(sql);
  }

  @Override
  public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {

  }

  public ArrayList<Focus> queryFocusList() {
    SQLiteDatabase db = instance.getReadableDatabase();
    Cursor cursor = db.query(FocusTable.TABLE_NAME, null, null, null, null, null, FocusTable.FOCUS_ENDTIME + " DESC ");
    ArrayList<Focus> list = new ArrayList<>();
    if (cursor != null) {
      while (cursor.moveToNext()) {
//        int id = getInt(cursor, FocusTable._ID);
        int startTime = getInt(cursor, FocusTable.FOCUS_STARTTIME);
        int endTime = getInt(cursor, FocusTable.FOCUS_ENDTIME);
        int duration = getInt(cursor, FocusTable.FOCUS_DURATION);
//        int createTime = getInt(cursor, FocusTable.FOCUS_CREATE_TIME);

        Focus Focus = new Focus();
//        Focus.setId(id);
//        Focus.setName(name);
        Focus.setStartTime(startTime);
        Focus.setEndTime(endTime);
        Focus.setDuration(duration);
        //少于60秒，即1分钟以内不显示
        if(duration < FocusUtils.SECONDS_IN_MIN) {
          continue;
        }
        list.add(Focus);
      }
      cursor.close();
    }
    return list;
  }

  public int queryTodaySeconds(int time) {

    int daySeconds = 60 * 60 * 24;
    int today = time - time % daySeconds;
    int tomorrowDay = today + daySeconds;

    SQLiteDatabase db = instance.getReadableDatabase();
    Cursor cursor = db.rawQuery("select total(" + FocusTable.FOCUS_DURATION + ") as " +
            FocusTable.FOCUS_DURATION + " from " + FocusTable.TABLE_NAME
            + " where " + FocusTable.FOCUS_ENDTIME + " >= ? and " + FocusTable.FOCUS_ENDTIME + "<= ?",
        new String[]{String.valueOf(today), String.valueOf(tomorrowDay)});

    int todaySeconds = 0;
    if (cursor != null) {
      if (cursor.moveToFirst()) {
        todaySeconds = getInt(cursor, FocusTable.FOCUS_DURATION);
      }
      cursor.close();
    }
    return todaySeconds;
  }

  private String getString(Cursor cursor, String columnName) {
    return cursor.getString(cursor.getColumnIndex(columnName));
  }

  private int getInt(Cursor cursor, String columnName) {
    return cursor.getInt(cursor.getColumnIndex(columnName));
  }

  public void saveFocus(Focus focus) {
    SQLiteDatabase db = instance.getWritableDatabase();
    ContentValues values = new ContentValues();
    values.put(FocusTable.FOCUS_STARTTIME, focus.getStartTime());
    values.put(FocusTable.FOCUS_ENDTIME, focus.getEndTime());
    values.put(FocusTable.FOCUS_DURATION, focus.getDuration());
    db.insert(FocusTable.TABLE_NAME, null, values);
  }

  /**
   * 将完成的专注存到sqlite数据库中
   *
   * @param durSeconds 专注时长，单位秒
   */
  public void saveFocus(int durSeconds) {
    Focus focus = new Focus();
    focus.setDuration(durSeconds);
    long now = System.currentTimeMillis();
    int endTime = (int) (now / FocusUtils.MILLIS_IN_SECOND);

    int startTime = endTime - durSeconds;
    focus.setEndTime(endTime);
    focus.setStartTime(startTime);
    saveFocus(focus);
  }

  public int queryTotalSeconds() {
    SQLiteDatabase db = instance.getReadableDatabase();
    int totalSeconds = 0;
    Cursor cursor = db.rawQuery("select total(" + FocusTable.FOCUS_DURATION + ") as " + FocusTable.FOCUS_DURATION + " from " + FocusTable.TABLE_NAME, null);
    if (cursor != null) {
      if (cursor.moveToFirst()) {
        totalSeconds = getInt(cursor, FocusTable.FOCUS_DURATION);
      }
      cursor.close();
    }
    return totalSeconds;
  }

  public void clearFocus() {
    SQLiteDatabase db = instance.getWritableDatabase();
    db.delete(FocusTable.TABLE_NAME, null, null);
  }
}
